﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Linq.Expressions;
    

namespace CMS.DataLibrary
{
    /*此类为增删查改服务
     * Find() +2重载
     * FindList()
     * FindPageList();
     * Add();
     * Update();
     * Delete();
     * Count();
     * Save();
     * IsContains();
     */ 
    public class Repository<T> where T : class
    {
        public DbContext DbContext { get; set; }

        public Repository() { }
        public Repository(DbContext dbContext)
        {
            DbContext = dbContext;
        }

        //<summary>查找实体</summary>
        ///<param name = "ID">实体主键</param>
        public T Find(int ID)
        {
            return DbContext.Set<T>().Find(ID);
        }
       
        //<summary>查找实体</summary>
        ///<param name = "where">查询Lambda表达式</param>
        public T Find(Expression<Func<T, bool>> where)
        {
            return DbContext.Set<T>().SingleOrDefault(where);
        }

        //<summary>查找实体列表</summary>
        public IQueryable<T> FindList()
        {
            return DbContext.Set<T>();
        }

        /// <summary>
        /// 查找列表
        /// </summary>
        /// <param name="where">lambda表达式</param>
        /// <param name="orderParams">排序参数</param>
        /// <param name="number">获取的数量【0-不启用】</param>
        /// <returns></returns>
        public IQueryable<T> FindList(Expression<Func<T, bool>> where, OrderParam[] orderParams, int number)
        {
            var list = DbContext.Set<T>().Where(where);
            var _orderParams = Expression.Parameter(typeof(T), "o");

            if(orderParams != null && orderParams.Length > 0)
            {
                for(int i = 0; i < orderParams.Length; i++)
                {
                    //获取属性名
                    var _property = typeof(T).GetProperty(orderParams[i].PropertyName);
                    //创建body
                    var _orderAccess = Expression.MakeMemberAccess(_orderParams, _property);
                    var _orderByExp = Expression.Lambda(_orderAccess, _orderParams);
                    string _orderName = orderParams[i].Method == OrderMethod.ASC ? "OrderBy" : "OrderByDescending";
                    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), _orderName, new Type[] { typeof(T), _property.PropertyType }, list.Expression, Expression.Quote(_orderByExp));
                    list = list.Provider.CreateQuery<T>(resultExp);
                }
            }

            if (number > 0)
                list = list.Take(number);

            return list;
        }

        /// <summary>
        /// 查找实体列表
        /// </summary>
        /// <param name="where">查询Lambda表达式</param>
        /// <returns></returns>
        public IQueryable<T> FindList(Expression<Func<T, bool>> where)
        {
            return DbContext.Set<T>().Where(where);
        }

        /// <summary>
        /// 查找实体列表
        /// </summary>
        /// <param name="where">查询Lambda表达式</param>
        /// <param name="number">获取的记录数量</param>
        /// <returns></returns>
        public IQueryable<T> FindList(Expression<Func<T, bool>> where, int number)
        {
            return DbContext.Set<T>().Where(where).Take(number);
        }

        /// <summary>
        /// 查找实体列表
        /// </summary>
        /// <param name="where">查询Lambda表达式</param>
        /// <param name="orderParam">排序参数</param>
        /// <returns></returns>
        public IQueryable<T> FindList(Expression<Func<T, bool>> where, OrderParam orderParam)
        {
            return FindList(where, orderParam, 0);
        }

        /// <summary>
        /// 查找实体列表
        /// </summary>
        /// <param name="where">查询Lambda表达式</param>
        /// <param name="orderParam">排序参数</param>
        /// <param name="number">获取的记录数量【0-不启用】</param>
        public IQueryable<T> FindList(Expression<Func<T, bool>> where, OrderParam orderParam, int number)
        {
            OrderParam[] _orderParams = null;
            if (orderParam != null) _orderParams = new OrderParam[] { orderParam };
            return FindList(where, _orderParams, number);
        }

        ///<summary>
        /// 查找分页列表
        /// </summary>
        /// <param name="pageSize">每页记录数。必须大于1</param>
        /// <param name="pageIndex">页码。首页从1开始，页码必须大于1</param>
        /// <param name="totalItems">总记录数</param>
        public IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalItems)
        {
            OrderParam orderParams = null;

            return FindPageList(pageSize, pageIndex, out totalItems, orderParams);
        }

        /// <summary>
        /// 查找分页列表
        /// </summary>
        /// <param name="pageSize">每页记录数。必须大于1</param>
        /// <param name="pageIndex">页码。首页从1开始，页码必须大于1</param>
        /// <param name="totalNumber">总记录数</param>
        public IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalItems, OrderParam orderParam)
        {
            return FindPageList(pageSize, pageIndex, out totalItems, (T) => true, orderParam);
        }

        public IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalItems, Expression<Func<T, bool>> where)
        {
            OrderParam param = null;
            return FindPageList(pageSize, pageIndex, out totalItems, where, param);
        }

        public IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalItems, Expression<Func<T, bool>> where, OrderParam orderParam)
        {
            OrderParam[] _orderParams = null;
            if (orderParam != null)
                _orderParams = new OrderParam[] { orderParam };

            return FindPageList(pageSize, pageIndex, out totalItems, where, _orderParams);
        }

      
        /// <summary>
        /// 查找分页列表
        /// </summary>
        /// <param name="pageSize">每页记录数。必须大于1</param>
        /// <param name="pageIndex">页码。首页从1开始，页码必须大于1</param>
        /// <param name="totalItems">总记录数</param>
        /// <param name="where">查询表达式</param>
        /// <param name="orderParams">排序【null-不设置】</param>
        public IQueryable<T> FindPageList(int pageSize, int pageIndex, out int totalItems, Expression<Func<T,bool>> where, OrderParam[] orderParams)
        {
            if(pageIndex < 1)
                pageIndex = 1;
            if(pageSize < 1)
                pageSize = 10;
            IQueryable<T> list = DbContext.Set<T>().Where(where);

            //创建输入参数
            var _orderParams = Expression.Parameter(typeof(T), "o");

            if(orderParams.Length > 0 && orderParams != null)
            {
                for(int i = 0; i < orderParams.Length; i++)
                {
                    //根据属性名获取属性
                    var _property = typeof(T).GetProperty(orderParams[i].PropertyName);
                    //创建一个访问属性的表达式,body
                    var _propertyAccess = Expression.MakeMemberAccess(_orderParams, _property);
                    //_orderParams => _orderParams._property
                    var _orderExp = Expression.Lambda(_propertyAccess, _orderParams);
                    string _orderName = orderParams[i].Method == OrderMethod.ASC ? "OrderBy" : "OrderByDescending";
                    MethodCallExpression resultExp = Expression.Call(typeof(Queryable), _orderName, new Type[] {
                        typeof(T),
                        _property.PropertyType }, list.Expression, Expression.Quote(_orderExp));
                    list = list.Provider.CreateQuery<T>(resultExp);
                }
            }

            totalItems = list.Count();

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize);
        }
 
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响的对象的数目</returns>
        public int Add(T entity)
        {
            return Add(entity, true);
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="isSave">是否立即保存</param>
        /// <returns>在“isSave”为True时返回受影响的对象的数目，为False时直接返回0</returns>
        public int Add(T entity, bool isSave)
        {
            DbContext.Set<T>().Add(entity);
            return isSave ? DbContext.SaveChanges() : 0;
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="entites">实体列表</param>
        /// <returns>受影响的数量</returns>
        public int Add(IEnumerable<T> entites)
        {
            DbContext.Set<T>().AddRange(entites);
            return DbContext.SaveChanges();
        }

         /// <summary>
        /// 更新实体【立即保存】
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响的对象的数目</returns>
        public int Update(T entity)
        {
            return Update(entity, true);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="isSave">是否立即保存</param>
        /// <returns>手印下的对象数目   </returns>
        public int Update(T entity, bool isSave)
        {
            DbContext.Set<T>().Attach(entity);
            DbContext.Entry(entity).State = EntityState.Modified;

            return isSave ? DbContext.SaveChanges() : 0;
        }

        /// <summary>
        /// 删除实体【立即保存】
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>受影响的对象的数目</returns>
        public int Delete(T entity)
        {
            return Delete(entity, true);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="isSave">是否立即保存</param>
        /// <returns>在“isSave”为True时返回受影响的对象的数目，为False时直接返回0</returns>
        public int Delete(T entity,bool isSave)
        {
            DbContext.Set<T>().Attach(entity);
            DbContext.Entry<T>(entity).State = EntityState.Deleted;
            return isSave ? DbContext.SaveChanges() : 0;
        }

        /// <summary>
        /// 批量删除实体
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响的对象的数目</returns>
        public int Delete(IEnumerable<T> entities)
        {
            DbContext.Set<T>().RemoveRange(entities);
            return DbContext.SaveChanges();
        }
        /// <summary>
        /// 记录数
        /// </summary>
        /// <returns>返回总数目</returns>
        public int Count()
        {
            return DbContext.Set<T>().Count();
        }

        /// <summary>
        /// 有条件的记录数
        /// </summary>
        /// <param name="where">Lamdab表达式</param>
        /// <returns></returns>
        public int Count(Expression<Func<T, bool>> where)
        {
            return DbContext.Set<T>().Count(where);
        }

        /// <summary>
        /// 检查对象是否存在
        /// </summary>
        /// <param name="where">表达式</param>
        /// <returns></returns>
        public bool IsContains(Expression<Func<T,bool>> where)
        {
            return Count(where) > 0;
        }

        /// <summary>
        /// 保存数据【在Add、Upate、Delete未立即保存的情况下使用】
        /// </summary>
        /// <returns>受影响的记录数</returns>
        public int Save()
        {
            return DbContext.SaveChanges();
        }

    }
}
